package dbinit;

import java.util.Iterator;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import core.product.model.Product;
import core.util.HibernateCoreUtil;
import core.util.database.index.model.ProductSearchIndex;

public class InitProductSearchIndex 
{
	public static ProductSearchIndex getProductSearchIndexByProduct(Product p)
	{
		ProductSearchIndex psi = null ;
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		try
		{
			transaction = session.beginTransaction();
			Iterator <ProductSearchIndex> psisItr = session.createQuery("from ProductSearchIndex psi where psi.result=:p").setEntity("p", p).list().iterator();
			while(psisItr.hasNext())
			{
				psi = psisItr.next();
				break ;
			}
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return psi ;
	}
	public static void update(ProductSearchIndex psi , String searchKey)
	{
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		try
		{
			transaction = session.beginTransaction();
			psi.setSearchKey(searchKey);
			session.update(psi);
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		
	}
	public static Long doinit(String searchKey , Long productId)
	{
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Long uuid = null ;
		Product p = InitProduct.getProductByUuid(productId) ;
		ProductSearchIndex psi = getProductSearchIndexByProduct(p);
		if(psi == null)
		{
			psi = new ProductSearchIndex();
			psi.setResult(p);
			psi.setSearchKey(searchKey);
			try
			{
				transaction = session.beginTransaction();
				uuid = (Long)session.save(psi);
				transaction.commit();
			}
			catch(HibernateException he)
			{
				he.printStackTrace();
			}
			finally 
			{
				session.close();
			}
		}
		else
		{
			update(psi ,searchKey );
			uuid = psi.getUuid();
		}
		return uuid ;
	}
}
